package com.example.srm.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.srm.auth.anno.Authority;
import com.example.srm.common.controller.BaseController;
import com.example.srm.constant.ProjectApplicationConstant;
import com.example.srm.constant.ProjectStatusConstant;
import com.example.srm.domain.TProject;
import com.example.srm.domain.TUpdateApplication;
import com.example.srm.domain.TUser;
import com.example.srm.domain.vo.Result;
import com.example.srm.project.service.TProjectService;
import com.example.srm.project.service.TUpdateApplicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author: admin
 * @time: 2021/12/1 8:17
 * @describe: 项目变更controller
 */
@RestController
@RequestMapping("/update_application")
@Slf4j
@CrossOrigin
public class TUpdateApplicationController extends BaseController<TUpdateApplicationService, TUpdateApplication> {
    @Autowired
    private TProjectService tProjectService;

    /**
     * 变更申请
     * @param tUpdateApplication 前端发送的变更数据
     * @param request 请求信息
     * @return 是否保存成功
     * @throws Exception
     */
    @Override
    @Authority(auth = "account:project:updateApplication")
    public Result save(@RequestBody TUpdateApplication tUpdateApplication, HttpServletRequest request) throws Exception {
        try {
            beforeSave(tUpdateApplication);
            //根据项目id查询项目具体信息
            TProject tProject = tProjectService.getById(tUpdateApplication.getProjectId());
            //得到 未结题 的状态码
            int notConclusionCode = ProjectStatusConstant.NOT_CONCLUSION.getCode();
            //得到 变更失败 的状态码
            int failUpdateAuditCode = ProjectStatusConstant.FAIL_UPDATE_AUDIT.getCode();
            //得到 结题失败 的状态码
            int failConcludeAuditCode = ProjectStatusConstant.FAIL_CONCLUDE_AUDIT.getCode();
            //得到 结题失败 的状态码
            int failProjectAudit = ProjectStatusConstant.FAIL_PROJECT_AUDIT.getCode();
            //得到 未申报 的状态码
            int successUpdateAuditCode = ProjectStatusConstant.SUCCESS_UPDATE_AUDIT.getCode();
            //得到 草稿 的状态码
            int notDeclaredCode = ProjectStatusConstant.NOT_DECLARED.getCode();
            //得到项目当前的状态
            Integer tProjectStatus = tProject.getStatus1();
            //判断项目当前的状态是否可以进行申请变更
            if (tProjectStatus!=notConclusionCode
                    &&tProjectStatus!=failConcludeAuditCode
                    &&tProjectStatus!=failUpdateAuditCode
                    &&tProjectStatus!=successUpdateAuditCode
                    &&tProjectStatus!=notDeclaredCode
                    &&tProjectStatus!=failProjectAudit){
                return new Result().setMsg("当前项目状态不能进行该操作");
            }
            //根据项目id 查询项目是否申请变更过
            TUpdateApplication tUpdateApplicationByProjectId = baseIService.getOne(new QueryWrapper<TUpdateApplication>().eq("project_id", tUpdateApplication.getProjectId()));
            //得到项目当前变更申请的name
            String projectApplicationStatusName = ProjectApplicationConstant.ON_APPLIACTION.getName();
            //用于保存修改或保存项目申请变更信息是否成功
            boolean flag =false;
            //如果项目未申请变更过
            if (tUpdateApplicationByProjectId==null){
                //设置项目申请变更信息
                tUpdateApplicationByProjectId = setProjectApplicationInfo(tUpdateApplication, projectApplicationStatusName, request);
                //保存申请变更信息
                flag =  baseIService.save(tUpdateApplicationByProjectId);
            }else {
                //将原有的变更信息改为传入的变更信息
                tUpdateApplication.setStatus(projectApplicationStatusName).setId(tUpdateApplicationByProjectId.getId());
                //修改申请变更状态
                flag = baseIService.updateById(tUpdateApplication);
            }

            //修改项目当前状态
            UpdateWrapper<TProject> updateWrapper = new UpdateWrapper<TProject>()
                    .eq("id", tUpdateApplicationByProjectId.getProjectId()) //设置根据id进行修改
                    .set("status", ProjectStatusConstant.UPDATE_AUDIT.getCode()); //设置修改的状态为变更申请中
            //进行修改
            boolean update = tProjectService.update(updateWrapper);
            return new Result().setSuccess(flag&&update);
        }catch (Exception e){
            log.error("保存失败",e);
            return new Result().setMsg("变更失败："+e.getMessage());
        }
    }
    /**
     * 项目变更驳回
     * @param tUpdateApplication 前端发送的变更数据
     * @param request 请求信息
     * @return 是否成功  conclude_application
     * @throws Exception
     */
    @PutMapping("/not_pass")
    @Authority(auth = "account:projectUpdate:notpass")
    public Result not_pass(@RequestBody TUpdateApplication tUpdateApplication, HttpServletRequest request) throws Exception {
        try {
            //得到项目当前申请变更的name【申报失败】
            String projectApplicationStatus = ProjectApplicationConstant.FAIL_APPLICATION.getName();
            //得到项目状态的code【表更失败】
            int projectStatusCode = ProjectStatusConstant.FAIL_UPDATE_AUDIT.getCode();
            boolean flag = updateProjectApplicationStatusAndProjectStatus(tUpdateApplication, projectApplicationStatus, projectStatusCode, request);
            return new Result().setSuccess(flag);
        }catch (Exception e){
            log.error("申报失败",e);
            return new Result().setMsg("申报失败，请检查参数是否合法."+e.getMessage());
        }
    }

    /**
     * 项目变更通过
     * @param tUpdateApplication
     * @param request
     * @return
     * @throws Exception
     */
    @PutMapping("/pass")
    @Authority(auth = "account:projectUpdate:pass")
    public Result pass(@RequestBody TUpdateApplication tUpdateApplication, HttpServletRequest request) throws Exception {
        try {
            //得到项目当前申请变更的name
            String projectApplicationStatus = ProjectApplicationConstant.SUCCESS_APPLICATION.getName();
            //得到项目状态的code(变更中【需要重新申报、不能结题、可以再次变更】）
            int projectStatusCode = ProjectStatusConstant.SUCCESS_UPDATE_AUDIT.getCode();
            boolean flag = updateProjectApplicationStatusAndProjectStatus(tUpdateApplication, projectApplicationStatus, projectStatusCode, request);
            return new Result().setSuccess(flag);
        }catch (Exception e){
            log.error("申报失败",e);
            return new Result().setMsg("申报失败，请检查参数是否合法."+e.getMessage());
        }
    }




    /**
     * 修改项目状态以及项目申报状态
     * @param tUpdateApplication 前端发送的申报数据
     * @param applicationStatusName 申报状态名
     * @param projectStatusCode 项目状态
     * @param request 请求信息
     * @return 是否成功
     */
    public boolean updateProjectApplicationStatusAndProjectStatus(TUpdateApplication tUpdateApplication,String applicationStatusName,int projectStatusCode, HttpServletRequest request){
        //设置项目实体类
//        TUpdateApplication tUpdateApplicationInFo = setProjectApplicationInfo(tUpdateApplication, applicationStatusName, request);
        tUpdateApplication.setStatus(applicationStatusName);
        //修改项目申报状态
//        boolean save = baseIService.updateById(tUpdateApplicationInFo);
        boolean save = baseIService.updateById(tUpdateApplication);
        //修改项目当前状态
        UpdateWrapper<TProject> updateWrapper = new UpdateWrapper<TProject>()
//                .eq("id", tUpdateApplicationInFo.getProjectId()) //设置根据id进行修改
                .eq("id", tUpdateApplication.getProjectId()) //设置根据id进行修改
                .set("status", projectStatusCode); //设置修改的状态为申报失败或者成功
        //进行修改项目状态
        boolean update = tProjectService.update(updateWrapper);
        return save&&update;
    }

    /**
     * 设置项目申报实体类
     * @param tUpdateApplication 前端发送的申报对象
     * @param applicationStatusName 项目申报的状态
     * @param request 请求信息
     * @return 项目申报实体类
     */
    public TUpdateApplication setProjectApplicationInfo(TUpdateApplication tUpdateApplication, String applicationStatusName, HttpServletRequest request){
        //从session中取出用户信息
        TUser userinfo = (TUser) request.getSession().getAttribute("USERINFO");
        //赋值申报人
        tUpdateApplication.setApplicant(userinfo.getUserName());
        //赋值申报时间
        tUpdateApplication.setApplicateTime(new Date());
        //设置申报状态
        tUpdateApplication.setStatus(applicationStatusName);
        return tUpdateApplication;
    }
}
